package com.daxt.controller.filemanager;

import java.util.*;
import java.util.stream.Collectors;

import com.daxt.mapper.archives.ArchivesTestingFourRecordMapper;
import com.daxt.model.dic.DicFourSex;
import com.daxt.model.dic.DicFourSexClassify;
import com.daxt.model.dto.fourSexTest.TestFourContentDto;
import com.daxt.model.dto.fourSexTest.TestFourDto;
import com.daxt.model.service.archives.vo.ArchivesTestingFourRecord;
import com.daxt.utils.BaseUtil;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.archives.ArchivesTestingFourMapper;
import com.daxt.mapper.archives.ArchivesTestingFourMetadataMapper;
import com.daxt.model.service.archives.vo.ArchivesTestingFour;
import com.daxt.model.service.archives.vo.ArchivesTestingFourMetadata;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "四性检查")
@RestController
@RequestMapping("/fileManager")
public class TestingFourController {

    @Autowired
    private ArchivesTestingFourMapper archivesTestingFourMapper;
    @Autowired
    private ArchivesTestingFourMetadataMapper archivesTestingFourMetadataMapper;
    @Autowired
    private ArchivesTestingFourRecordMapper archivesTestingFourRecordMapper;

    @ApiOperation(value = "四性检测列表", notes = "")
    @GetMapping("/testing/four/{source}")
    public Result<List<ArchivesTestingFour>> list(@ApiParam("来源 例：OA ") @PathVariable("source") String source) {
        QueryWrapper<ArchivesTestingFour> queryWrapper = new QueryWrapper<ArchivesTestingFour>();
        queryWrapper.eq("source", source);
        List<ArchivesTestingFour> selectList = archivesTestingFourMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", selectList);
    }

    @ApiOperation(value = "四性检测保存", notes = "")
    @PostMapping("/testing/four")
    public Result<ArchivesTestingFour> save(@RequestBody List<ArchivesTestingFour> archivesTestingFours) {
        if (archivesTestingFours != null && archivesTestingFours.size() > 0) {
            for (ArchivesTestingFour archivesTestingFour : archivesTestingFours) {
                QueryWrapper<ArchivesTestingFour> wrapper = new QueryWrapper<ArchivesTestingFour>();
//			wrapper.eq("typeId", archivesTestingFour.getTypeId());
                wrapper.eq("testType", archivesTestingFour.getTestType());
                wrapper.eq("source", archivesTestingFour.getSource());
                archivesTestingFourMapper.delete(wrapper);
                archivesTestingFourMapper.insert(archivesTestingFour);
            }
        } else {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", null);
        }

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }


    @ApiOperation(value = "四性检测结果", notes = "")
    @GetMapping("/fourTest/result/{docId}")
    public Result<Map> fourTestResult(@ApiParam("文件ID") @PathVariable("docId") String docId) {


        QueryWrapper<ArchivesTestingFourRecord> queryWrapper = new QueryWrapper<ArchivesTestingFourRecord>();
        queryWrapper.select("id," +
                        "testType," +
                        "testClassify," +
                        "docId," +
                        "field," +
                        "case when (count(case when test='false' then 'false'  end ))>0 then 'false' else 'true' end as test," +
                        "source," +
                        "describes," +
                        "createBy," +
                        "updateBy," +
                        "createTime," +
                        "updateTime ");
        queryWrapper.eq("docId", docId);
        //queryWrapper.groupBy("testClassify");
        queryWrapper.orderByAsc("testType");
        List<ArchivesTestingFourRecord> atfrList = archivesTestingFourRecordMapper.selectList(queryWrapper);

        Map m = new LinkedHashMap();

        buildResult(atfrList, DicFourSex.TYPE_1, m);
        buildResult(atfrList, DicFourSex.TYPE_2, m);
        buildResult(atfrList, DicFourSex.TYPE_3, m);
        buildResult(atfrList, DicFourSex.TYPE_4, m);

        return ResultUtil.success(m);

    }


    @ApiOperation(value = "元数据列表 ", notes = "")
    @GetMapping("/testing/four/metadata")
    public Result<List<ArchivesTestingFourMetadata>> metadataList(
            @ApiParam("类型 1-基础字段、2-文件字段 ") @RequestParam(value = "type", required = false) String type
            ,@ApiParam("系统类型") @RequestParam(value = "systemType", required = false) String systemType) {
        QueryWrapper<ArchivesTestingFourMetadata> wrapper = new QueryWrapper<ArchivesTestingFourMetadata>();
        if (StringUtils.isNotEmpty(type)) wrapper.eq("type", type);
        if (StringUtils.isNotEmpty(systemType)) wrapper.like("systemType", systemType);
        List<ArchivesTestingFourMetadata> selectList = archivesTestingFourMetadataMapper.selectList(wrapper);
        return ResultUtil.success(selectList);
    }
//	@ApiOperation(value = "元数据列表 ", notes = "")
//	@GetMapping("/testing/four/metadata/{typeId}")
//	public Result<List<ArchivesTestingFourMetadata>> metadataList(@PathVariable("typeId")String typeId) {
//		QueryWrapper<ArchivesTestingFourMetadata> wrapper=new QueryWrapper<ArchivesTestingFourMetadata>();
//		wrapper.eq("typeId", typeId);
//		List<ArchivesTestingFourMetadata> selectList = archivesTestingFourMetadataMapper.selectList(wrapper);
//		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "",selectList);
//	}


//	@ApiOperation(value = "元数据保存 ", notes = "")
//	@PostMapping("/testing/four/metadata")
//	public Result<ArchivesTestingFour> metadataSave(@RequestBody ArchivesTestingFourMetadata archivesTestingFourMetadata) {
//		QueryWrapper<ArchivesTestingFourMetadata> wrapper=new QueryWrapper<ArchivesTestingFourMetadata>();
//		wrapper.eq("typeId", archivesTestingFourMetadata.getTypeId());
//		wrapper.eq("dataKey", archivesTestingFourMetadata.getDataKey());
//		archivesTestingFourMetadataMapper.delete(wrapper);
//		archivesTestingFourMetadataMapper.insert(archivesTestingFourMetadata);
//		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "",null);
//	}

//	@ApiOperation(value = "元数据删除 ", notes = "")
//	@DeleteMapping("/testing/four/metadata/{id}")
//	public Result<ArchivesTestingFour> metadataDel(@PathVariable("id")String id) {
//		archivesTestingFourMetadataMapper.deleteById(id);
//		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "",null);
//	}


    private void buildResult(List<ArchivesTestingFourRecord> atfrList, DicFourSex fs, Map m) {
        //真实性
        List<ArchivesTestingFourRecord> typeList = atfrList.stream().filter(bean -> bean.getTestType().equals(fs.getKey())).collect(Collectors.toList());

        if(!BaseUtil.listIsNotNullElement(typeList)) return;

//		Map infoList = new HashMap();
        List<TestFourContentDto> infoList = new ArrayList();
        typeList.forEach((ArchivesTestingFourRecord atfrBean) -> {

            TestFourContentDto dto = new TestFourContentDto();

            for (DicFourSexClassify fsc : DicFourSexClassify.values()) {
                if (atfrBean.getTestClassify().equals(fsc.getKey())) {
                    dto.setClassNumber(fsc.getValue());
                    dto.setClassNum(fsc.getKey());

                }
            }
//			for (DicFourSex fs : DicFourSex.values()) {
//				if(atfrBean.getTestType().equals(fs.getKey())){
//					dto.setNumber(fs.getKey());
//					dto.setNumberName(fs.getValue());
//
//				}
//			}
            dto.setNumber(fs.getKey());
            dto.setNumberName(fs.getValue());
            dto.setResult(atfrBean.getTest().equals("true") ? "通过" : "不通过");
            infoList.add(dto);


        });

        List<ArchivesTestingFourRecord> passList = typeList.stream().filter(bean -> bean.getTest().equals("true")).collect(Collectors.toList());

        TestFourDto tfDot = new TestFourDto();
        tfDot.setTotalNum(typeList.size());
        tfDot.setSuccessNum(passList.size());
        tfDot.setFailureNum(typeList.size() - passList.size());
        tfDot.setTestContent(infoList);


        m.put(fs.getValue(), tfDot);
    }
}
